from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
import os
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
from process_manager import ProcessManager

# 配置日志
logging.basicConfig(
    filename='process_manager_service.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class ProcessManagerService(win32serviceutil.ServiceFramework):
    _svc_name_ = "ProcessManagerService"
    _svc_display_name_ = "Process Manager Service"
    _svc_description_ = "Windows进程管理服务"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)
        self.is_running = False

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)
        self.is_running = False

    def SvcDoRun(self):
        self.is_running = True
        try:
            self.main()
        except Exception as e:
            logging.error(f"服务运行错误: {str(e)}")
            self.is_running = False

    def main(self):
        app = Flask(__name__)
        CORS(app)
        process_manager = ProcessManager()

        # 确保static目录存在
        if not os.path.exists('static'):
            os.makedirs('static')

        @app.route('/')
        def index():
            return send_from_directory('static', 'index.html')

        @app.route('/api/processes', methods=['GET'])
        def get_processes():
            return jsonify(process_manager.get_all_processes())

        @app.route('/api/processes', methods=['POST'])
        def add_process():
            data = request.json
            if not data:
                return jsonify({'error': '无效的请求数据'}), 400

            if 'name' not in data or 'command' not in data:
                return jsonify({'error': '缺少必要的参数'}), 400

            # 检查文件是否存在
            if not os.path.exists(data['command']):
                return jsonify({'error': '可执行文件不存在'}), 400

            # 检查文件扩展名
            if not data['command'].lower().endswith('.exe'):
                return jsonify({'error': '只能选择.exe文件'}), 400

            success, message = process_manager.start_process(data['name'], data['command'])
            if success:
                return jsonify({'message': message})
            else:
                return jsonify({'error': message}), 400

        @app.route('/api/processes/<name>', methods=['DELETE'])
        def stop_process(name):
            success, message = process_manager.stop_process(name)
            if success:
                return jsonify({'message': message})
            else:
                return jsonify({'error': message}), 400

        @app.route('/api/processes/<name>/remove', methods=['DELETE'])
        def remove_process(name):
            success, message = process_manager.remove_process(name)
            if success:
                return jsonify({'message': message})
            else:
                return jsonify({'error': message}), 400

        @app.route('/api/running-processes', methods=['GET'])
        def get_running_processes():
            return jsonify(process_manager.get_running_processes())

        # 启动监控线程
        process_manager.start_monitoring()

        # 启动Flask应用
        app.run(host='0.0.0.0', port=5000)

def run_as_app():
    """以普通应用程序方式运行"""
    app = Flask(__name__)
    CORS(app)
    process_manager = ProcessManager()

    # 确保static目录存在
    if not os.path.exists('static'):
        os.makedirs('static')

    @app.route('/')
    def index():
        return send_from_directory('static', 'index.html')

    @app.route('/api/processes', methods=['GET'])
    def get_processes():
        return jsonify(process_manager.get_all_processes())

    @app.route('/api/processes', methods=['POST'])
    def add_process():
        data = request.json
        if not data:
            return jsonify({'error': '无效的请求数据'}), 400

        if 'name' not in data or 'command' not in data:
            return jsonify({'error': '缺少必要的参数'}), 400

        # 检查文件是否存在
        if not os.path.exists(data['command']):
            return jsonify({'error': '可执行文件不存在'}), 400

        # 检查文件扩展名
        if not data['command'].lower().endswith('.exe'):
            return jsonify({'error': '只能选择.exe文件'}), 400

        success, message = process_manager.start_process(data['name'], data['command'])
        if success:
            return jsonify({'message': message})
        else:
            return jsonify({'error': message}), 400

    @app.route('/api/processes/<name>', methods=['DELETE'])
    def stop_process(name):
        success, message = process_manager.stop_process(name)
        if success:
            return jsonify({'message': message})
        else:
            return jsonify({'error': message}), 400

    @app.route('/api/processes/<name>/remove', methods=['DELETE'])
    def remove_process(name):
        success, message = process_manager.remove_process(name)
        if success:
            return jsonify({'message': message})
        else:
            return jsonify({'error': message}), 400

    @app.route('/api/running-processes', methods=['GET'])
    def get_running_processes():
        return jsonify(process_manager.get_running_processes())

    # 启动监控线程
    process_manager.start_monitoring()

    # 启动Flask应用
    app.run(host='0.0.0.0', port=5000)

if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] in ['install', 'remove', 'start', 'stop', 'restart']:
        # 服务模式
        if len(sys.argv) == 1:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(ProcessManagerService)
            servicemanager.StartServiceCtrlDispatcher()
        else:
            win32serviceutil.HandleCommandLine(ProcessManagerService)
    else:
        # 普通应用程序模式
        run_as_app() 